package thread;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 14
 * Time: 17:29
 */
//实现定时器
class MyTimeTask implements Comparable<MyTimeTask>{
    private Runnable runnable;
    private long time;
    public MyTimeTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    @Override
    public int compareTo(MyTimeTask o) {
        return (int)(this.time - o.time);
    }
    public Runnable getRunnable() {
        return runnable;
    }
    public long getTime() {
        return time;
    }
}
class MyTime {
    PriorityQueue<MyTimeTask> priorityQueue = new PriorityQueue<>();
    Object lock = new Object();
    public void schedule(Runnable runnable, long delay) {
        synchronized (lock) {
            priorityQueue.offer(new MyTimeTask(runnable, delay));
            lock.notify();
        }
    }
    public MyTime() {
        Thread t1 = new Thread(() -> {
            while(true) {
                synchronized (lock) {
                    while (priorityQueue.isEmpty()) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimeTask task = priorityQueue.peek();
                    long curTime = System.currentTimeMillis();
                    if (curTime >= task.getTime()) {
                        task.getRunnable().run();
                        priorityQueue.poll();
                    } else {
                        try {
                            lock.wait(task.getTime() - curTime);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        t1.start();
    }
}
class Test {
    public static void main(String[] args) {
        MyTime myTime = new MyTime();
        myTime.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(3000);
            }
        }, 3000);
        myTime.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(1000);
            }
        }, 1000);
        myTime.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(2000);
            }
        }, 2000);
    }
}
